package cn.itsource.pet.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.LoginInfoUtil;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.baidumap.DistanceUtil;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.pojo.info.LoginInfo;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
//Propagation.SUPPORTS:支持别人事务
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg, SearchMasterMsgQuery> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper msgMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Override
    public PageList<SearchMasterMsg> findPage(SearchMasterMsgQuery query) {
        //1.从redis里面获取店铺id
        Long shopId = LoginInfoUtil.getShopId();
        //1.分页查询
        //PageHelper.startPage(query.getPage(),query.getSize());
        //2.去xml查询数据
        query.setShopId(shopId);
        List<SearchMasterMsg> list = msgMapper.findAll(query);
        if (list.size() == 0){
            return new PageList<>();
        }

        //2.查询到店铺信息
        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        //String shopAddress = shop.getAddress();

        /*ArrayList<SearchMasterMsg> msgs = new ArrayList<SearchMasterMsg>();
        for (SearchMasterMsg item : list) {
            if (DistanceUtil.calTwoAddressOfDistance(shop.getAddress(), item.getAddress())<5000){
                msgs.add(item);
            }
        }*/

        //通过百度的工具类进行5km过滤
        //filter:过滤  item:list的实例对象 条件:店铺地址和宠物发布地址5km内判断 collect:收集成一个list
        List<SearchMasterMsg> msgList = list.stream().filter(item -> DistanceUtil.calTwoAddressOfDistance(shop.getAddress(), item.getAddress())<5000)
                .collect(Collectors.toList());

        if (msgList.size() == 0){
            return new PageList<>();
        }

        //分页  limit  skip:跳过  limit:分页
        List<SearchMasterMsg> resultList = msgList.stream().skip((query.getPage() - 1) * query.getSize()).limit(query.getSize()).collect(Collectors.toList());


        //4.返回自定义分页对象
        return new PageList<SearchMasterMsg>((long)msgList.size(),resultList);
    }
}
